<template>
  <div id="UserLoginPage">
    <h2 style="margin-bottom: 32px">
      {{ pageTitle }}
    </h2>
    <a-form
      :model="form"
      :style="{ width: '480px', margin: '0 auto' }"
      label-align="left"
      auto-label-width
      @submit="handleSubmit"
    >
      <a-form-item field="appName" label="应用名称">
        <a-input v-model="form.appName" placeholder="请输入应用名称" />
      </a-form-item>
      <a-form-item field="appDesc" label="应用描述">
        <a-input v-model="form.appDesc" placeholder="请输入应用描述" />
      </a-form-item>
      <a-form-item field="appIcon" label="应用图标">
        <div
          style="display: flex; flex-direction: column; gap: 12px; width: 100%"
        >
          <a-radio-group
            v-model="iconInputMode"
            type="button"
            style="width: 48%"
          >
            <a-radio value="link">填写图标链接</a-radio>
            <a-radio value="upload">上传图标</a-radio>
          </a-radio-group>

          <div v-if="iconInputMode === 'upload'">
            <PictureUploader
              :value="form.appIcon"
              :on-change="(value) => (form.appIcon = value)"
              biz="app_icon"
            />
          </div>

          <div v-else>
            <a-input
              v-model="form.appIcon"
              placeholder="请填入图标链接"
              allow-clear
            />
            <div v-if="form.appIcon" style="margin-top: 12px">
              <div style="margin-bottom: 4px; color: #999">图标预览：</div>
              <img
                :src="form.appIcon"
                alt="图标预览"
                style="
                  width: 80px;
                  height: 80px;
                  object-fit: contain;
                  border: 1px solid #eee;
                  border-radius: 8px;
                "
                @error="handleImageError"
              />
            </div>
          </div>
        </div>
      </a-form-item>

      <a-form-item field="appType" label="应用类型">
        <a-select
          v-model="form.appType"
          :style="{ width: '320px' }"
          placeholder="请选择应用类型"
        >
          <a-option
            v-for="(value, key) of APP_TYPE_MAP"
            :key="key"
            :value="Number(key)"
            :label="value"
          />
        </a-select>
      </a-form-item>
      <a-form-item field="scoringStrategy" label="评分策略">
        <a-select
          v-model="form.scoringStrategy"
          :style="{ width: '320px' }"
          placeholder="请选择评分策略"
        >
          <a-option
            v-for="(value, key) of APP_SCORING_STRATEGY_MAP"
            :key="key"
            :value="Number(key)"
            :label="value"
            :disabled="isScoringStrategyDisabled(key)"
          />
        </a-select>
      </a-form-item>

      <a-form-item>
        <a-button type="primary" html-type="submit" style="width: 120px"
          >提交
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { computed, defineProps, ref, watchEffect, withDefaults } from "vue";
import API from "@/api";
import { useLoginUserStore } from "@/store/userStore";
import message from "@arco-design/web-vue/es/message";
import { useRouter } from "vue-router";
import {
  addAppUsingPost,
  editAppUsingPost,
  getAppVoByIdUsingGet,
} from "@/api/appController";
import { APP_SCORING_STRATEGY_MAP, APP_TYPE_MAP } from "@/constant/app";
import PictureUploader from "@/components/PictureUploader.vue";

const pageTitle = computed(() => (props.id ? "修改应用" : "创建应用"));
const isScoringStrategyDisabled = (key: string | number) => {
  // 当 appType 为 0（得分类）时，禁止选择 AI（key 为 1）
  return form.value.appType === 0 && Number(key) === 1;
};

interface Props {
  id: string;
}

const props = withDefaults(defineProps<Props>(), {
  id: () => {
    return "";
  },
});
const oldApp = ref<API.AppVO>();
/**
 * 加载数据
 */
const loadData = async () => {
  if (!props.id) {
    return;
  }
  const res = await getAppVoByIdUsingGet({
    id: props.id,
  });
  if (res.data.code === 0 && res.data.data) {
    oldApp.value = res.data.data;
    form.value = res.data.data;
  } else {
    message.error("获取数据失败，" + res.data.message);
  }
};
watchEffect(() => {
  loadData();
});

const hasImageError = ref(false);
const handleImageError = (e: Event) => {
  if (!hasImageError.value) {
    hasImageError.value = true;
    const target = e.target as HTMLImageElement;
    target.src = "";
    message.error("图标链接无效，无法加载图片");
  }
};
const iconInputMode = ref<"upload" | "link">("link");

const router = useRouter();

const loginUserStore = useLoginUserStore();

const form = ref({
  appDesc: "",
  appIcon: "",
  appName: "",
  appType: 0,
  scoringStrategy: 0,
} as API.AppAddRequest);
watchEffect(() => {
  if (form.value.appType === 0 && form.value.scoringStrategy === 1) {
    form.value.scoringStrategy = 0;
  }
});

const handleSubmit = async () => {
  let res: any;
  if (props.id) {
    res = await editAppUsingPost({
      id: props.id,
      ...form.value,
    });
  } else {
    res = await addAppUsingPost(form.value);
  }
  if (res.data.code === 0) {
    await loginUserStore.fetchLoginUser();
    message.success("操作成功,即将跳转到应用详情页");
    setTimeout(() => {
      router.push(`/app/detail/${props.id || res.data.data}`);
    }, 3000);
  } else {
    message.error("操作失败" + res.data.message);
  }
};
</script>
